package cn.starlightsoftware.sherly.service.permission;

import cn.hutool.core.bean.BeanUtil;
import cn.starlightsoftware.sherly.controller.admin.permission.vo.RolePageReqVO;
import cn.starlightsoftware.sherly.controller.admin.permission.vo.RolePermissionUpdateReqVO;
import cn.starlightsoftware.sherly.controller.admin.permission.vo.RoleSaveReqVO;
import cn.starlightsoftware.sherly.db.mysql.permission.RoleMapper;
import cn.starlightsoftware.sherly.db.mysql.permission.RolePermissionMapper;
import cn.starlightsoftware.sherly.model.PageResult;
import cn.starlightsoftware.sherly.db.model.permission.RoleDO;
import cn.starlightsoftware.sherly.db.model.permission.RolePermissionDO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 谷子毅
 * @date 2024/4/27
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public PageResult<RoleDO> page(RolePageReqVO reqVO) {
        return roleMapper.selectPage(reqVO);
    }

    @Override
    public void save(RoleSaveReqVO reqVO) {
        roleMapper.insert(BeanUtil.copyProperties(reqVO, RoleDO.class));
    }

    @Override
    public void update(RoleSaveReqVO reqVO) {
        roleMapper.updateById(BeanUtil.copyProperties(reqVO, RoleDO.class));
    }

    @Override
    public RoleDO detail(String roleId) {
        return roleMapper.selectById(roleId);
    }

    @Override
    public void delete(String roleId) {
        roleMapper.deleteById(roleId);
    }

    @Override
    public List<RolePermissionDO> rolePermissionList(String roleId) {
        return rolePermissionMapper.selectList(RolePermissionDO::getRoleId, roleId);
    }

    @Override
    public void rolePermissionUpdate(RolePermissionUpdateReqVO reqVO) {
        rolePermissionMapper.delete(RolePermissionDO::getRoleId, reqVO.getRoleId());
        List<RolePermissionDO> list = reqVO.getPermissionIds()
                .stream()
                .map(permissionId -> new RolePermissionDO().setRoleId(reqVO.getRoleId()).setPermissionId(permissionId))
                .collect(Collectors.toList());

        rolePermissionMapper.insertBatch(list);
    }

    @Override
    public List<RoleDO> list() {
        return roleMapper.selectList();
    }
}
